package com.hailiang.saas.auth.service.impl;

import com.hailiang.saas.auth.common.DefaultUserDetails;
import com.hailiang.saas.auth.config.AuthenticationConfig;
import com.hailiang.saas.auth.service.CommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author : pangfuzhong
 * @description
 * @date : 2021/9/15 11:15
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AuthenticationConfig authenticationConfig;

    /**
     * 根据用户名加载用户
     * */
    @Override
    public UserDetails loadUserByUsername(String accountName) throws UsernameNotFoundException {
        // 获取用户
        try {
            DefaultUserDetails defaultUserDetails = CommonService.loadUserByUsername(this.authenticationConfig, accountName);
            if(Objects.isNull(defaultUserDetails)) {
                throw new UsernameNotFoundException("未查询到账号 [" + accountName + "] 信息");
            }

            return defaultUserDetails;
        } catch (Throwable e) {
            //e.printStackTrace();
            throw new UsernameNotFoundException(e.getMessage());
        }
    }
}
